<?php

/**
 * Created by PhpStorm.
 * User: shwy
 * Date: 2017/6/29
 * Time: 9:12
 * 商品管理接口
 */
class goods extends CI_Controller
{

    //todo 异常处理没完成,异常信息加在msg的返回信息中 try catch 事物处理
    public function __construct()
    {
        parent::__construct();
        $this->load->model('goods_model');
        $this->load->model('goodsImage_model');
        $this->load->model('goodsStockPrice_model');
        $this->load->model('goodsAttribute_model');
        $this->load->model('goodsCategory_model');
        $this->load->model('goodsSpecification_model');
        $this->load->model('warning_model');
    }

    /**
     * 商品新增/编辑
     */
    public function addOrEdit()
    {

        $goods = json_decode($_POST['product'],true);
        $goodsSpecification = json_decode($_POST['productSpecification'],true);
        $goodsStockPrice = json_decode($_POST['productStockPrice'],true);
        $goodsImage = json_decode($_POST['productImage'],true);
        // $goodsAttribute = json_decode($_POST['data']['productAttribute'],true);


        if ($_POST['isNew']) {
            if(!isset($goods['detail'])){
                $goods['detail'] = '';
            }

            $goods = [
                'ckId' => $goods['ckId'],//商品Id
                'product_no' => $goods['productNo'],//商品编号
                'name' => $goods['productName'],//商品类型id （2物料包、3书籍、4机器耗材、9打印机租赁、8供应商商品）
                'one_category' => $goods['oneCategoryId'],//二级分类id
                'two_category' => $goods['twoCategoryId'], //三级分类
                'three_category' => $goods['threeCategoryId'],
                'detail' => $goods['detail'],//详情
                'is_can_size' => $goods['isCanSize'],//0不启用,1启用
                'source' => '51ck',
                'create_time' => time(),
            ];


            $this->goods_model->trans_begin();

            try {

                $goodsResult = $this->goods_model->add($goods);

                if($goodsSpecification){
                    foreach ($goodsSpecification as $k=>$v){
                        if(!isset($v['parentSpecification'])){
                            $v['parentSpecification'] = '';
                        }
                        $goodsSpecificationData = [
                            'product_specificationId' => $v['productSpecificationId'], //商品组合id
                            'name' => $v['name'], //规格名
                            'product_id' => $v['productId'], //商品id
                            'parent_specification' => $v['parentSpecification'], //上级规格（为空即第一级规格）
                            'create_time' => time(),
                        ];

                        $goodsSpecificationResult = $this->goodsSpecification_model->add($goodsSpecificationData);
                    }
                }


                if($goodsStockPrice){
                    foreach ($goodsStockPrice as $k2=>$v2){
                        if(!isset($v2['specificationGroupNames'])){
                            $v2['specificationGroupNames'] = '暂无规格'; //没有规格的时候显示默认值
                        }
                        $goodsStockPriceData = [
                            'product_stock_priceId' => $v2['productStockPriceId'], //商品库存价格表id
                            'group_no' => $v2['groupNo'], //商品规格组合编号随机生成
                            'product_id' => $v2['productId'],
                            'specification_group_names' => $v2['specificationGroupNames'], //规格名的组合，多个以“，”隔开, 匹配规格
                            'stock' => $v2['stock'], //库存
                            'price' => $v2['price'], //价格
                            'create_time' => time(),
                        ];

                        $goodsStockPriceResult = $this->goodsStockPrice_model->add($goodsStockPriceData);
                    }
                }


                if($goodsImage){
                    foreach ($goodsImage as $k3=>$v3){
                        $goodsImageData = [
                            'product_imageId' => $v3['productImageId'], //商品图片Id
                            'product_id' => $v3['productId'], //商品id
                            'file_path' => $v3['filePath'], //文件路径（不包含ip地址）
                            'is_main' => $v3['isMain'], //0不是主图，1是主图
                            'create_time' => time(),
                        ];

                        $this->goodsImage_model->add($goodsImageData);
                    }
                }

                if($goodsResult && $goodsStockPriceResult ){
                    // 如果都为真，全部提交
                    $this->goods_model->trans_commit();
                    $this->goodsSpecification_model->trans_commit();
                    $this->goodsStockPrice_model->trans_commit();
                    $this->goodsImage_model->trans_commit();

                    $result = [
                        'ret' => 200,
                        'data' => '',
                        'msg' => '成功'
                    ];

                    echo json_encode($result,JSON_UNESCAPED_UNICODE);
                }else{

                    $result = [
                        'ret' => 4000,
                        'data' => '',
                        'msg' => '商品添加失败'
                    ];

                    echo json_encode($result,JSON_UNESCAPED_UNICODE);

                    throw new Exception('商品添加失败');
                }

            }catch (Exception $e){
                //如果出错，全部回滚
                __logInfo('商品新增的时候异常信息',$e->getMessage());
                $this->goods_model->trans_rollback();
                $this->goodsSpecification_model->trans_rollback();
                $this->goodsStockPrice_model->trans_rollback();
                $this->goodsImage_model->trans_rollback();

            }


        } else {
            if(!isset($goods['detail'])){
                $goods['detail'] = '';
            }
            //edit, 添加的时候先把数据库的都先删除
            //先根据id把所有满足where条件的数据删除
            $data = [
                'product_id' => $goods['ckId'], //商品组合id
            ];

            //编辑的时候先删除数据
            $this->goodsSpecification_model->remove($data);
            $this->goodsStockPrice_model->remove($data);
            $this->goodsImage_model->remove($data);


            //开启事物
            $this->goods_model->trans_begin();

            try{
                $goodsData = [
                    'product_no' => $goods['productNo'],//商品编号
                    'name' => $goods['productName'],//商品类型id （2物料包、3书籍、4机器耗材、9打印机租赁、8供应商商品）
                    'one_category' => $goods['oneCategoryId'],//二级分类id
                    'two_category' => $goods['twoCategoryId'], //三级分类
                    'three_category' => $goods['threeCategoryId'],
                    'detail' => $goods['detail'],//详情
                    'is_can_size' => $goods['isCanSize'],//0不启用,1启用
                    'source' => '51ck',
                    'update_time' => time(),
                ];

                $goodsWhere = [
                    'ckId' => $goods['ckId']//商品Id
                ];

                $goodsEditResult = $this->goods_model->edit($goodsData,$goodsWhere);

                if($goodsSpecification){
                    foreach ($goodsSpecification as $k=>$v){

                        if(isset($v['parentSpecification'])){
                            $goodsSpecificationData = [
                                'product_specificationId' => $v['productSpecificationId'], //商品组合id
                                'name' => $v['name'], //规格名
                                'product_id' => $v['productId'], //商品id
                                'parent_specification' => $v['parentSpecification'], //上级规格（为空即第一级规格）
                                'update_time' => time()
                            ];
                        }else{
                            $goodsSpecificationData = [
                                'product_specificationId' => $v['productSpecificationId'], //商品组合id
                                'name' => $v['name'], //规格名
                                'product_id' => $v['productId'], //商品id
                                'update_time' => time()
                            ];
                        }



                        $goodsSpecificationEditResult = $this->goodsSpecification_model->add($goodsSpecificationData);
                    }
                }


                if($goodsStockPrice){

                    foreach ($goodsStockPrice as $k2=>$v2){
                        if(isset($v2['specificationGroupNames'])){
                            $goodsStockPriceData = [
                                'product_stock_priceId' => $v2['productStockPriceId'], //商品库存价格表id
                                'group_no' => $v2['groupNo'], //商品规格组合编号随机生成
                                'product_id' => $v2['productId'],
                                'specification_group_names' => $v2['specificationGroupNames'], //规格名的组合，多个以“，”隔开, 匹配规格
                                'stock' => $v2['stock'], //库存
                                'price' => $v2['price'], //价格
                                'update_time' => time()
                            ];

                        }else{
                            $goodsStockPriceData = [
                                'product_stock_priceId' => $v2['productStockPriceId'], //商品库存价格表id
                                'group_no' => $v2['groupNo'], //商品规格组合编号随机生成
                                'product_id' => $v2['productId'],
                                'specification_group_names' => '暂无规格', //没有规格的时候显示默认值
                                'stock' => $v2['stock'], //库存
                                'price' => $v2['price'], //价格
                                'update_time' => time()
                            ];
                        }

                        $goodsStockPriceEditResult = $this->goodsStockPrice_model->add($goodsStockPriceData);
                    }
                }


                if($goodsImage){
                    foreach ($goodsImage as $k3=>$v3){
                        $goodsImageData = [
                            'product_imageId' => $v3['productImageId'], //商品图片Id
                            'product_id' => $v3['productId'], //商品id
                            'file_path' => $v3['filePath'], //文件路径（不包含ip地址）
                            'is_main' => $v3['isMain'], //0不是主图，1是主图
                            'update_time' => time()
                        ];

                        $this->goodsImage_model->add($goodsImageData);
                    }
                }

                if($goodsEditResult  && $goodsStockPriceEditResult){
                    // 如果都为真，全部提交
                    $this->goods_model->trans_commit();
                    $this->goodsSpecification_model->trans_commit();
                    $this->goodsStockPrice_model->trans_commit();
                    $this->goodsImage_model->trans_commit();

                    $result = [
                        'ret' => 200,
                        'data' => '',
                        'msg' => '成功'
                    ];

                    echo json_encode($result,JSON_UNESCAPED_UNICODE);
                }else{
                    $result = [
                        'ret' => 4000,
                        'data' => '',
                        'msg' => '商品添加失败'
                    ];

                    echo json_encode($result,JSON_UNESCAPED_UNICODE);

                    throw new Exception('商品编辑失败');
                }

            }catch (Exception $e){
                //如果出错，全部回滚
                __logInfo('商品编辑的时候异常信息',$e->getMessage());
                $this->goods_model->trans_rollback();
                $this->goodsSpecification_model->trans_rollback();
                $this->goodsStockPrice_model->trans_rollback();
                $this->goodsImage_model->trans_rollback();

            }

        }
    }


    /**
     * 库存修改接口
     */
    public function stockEdit()
    {

        $this->goodsStockPrice_model->trans_begin();
        try{
            $data = [
                'stock'=> $_POST['stock']  //库存
            ];

            $where = [
                'product_stock_priceId'=> $_POST['productStockPriceId']  //商品库存表Id
            ];

            $edit = $this->goodsStockPrice_model->edit($data,$where);

            if($edit){
                // 如果都为真，全部提交
                $this->goodsStockPrice_model->trans_commit();

                $result = [
                    'ret' => 200,
                    'data' => '',
                    'msg' => '成功'
                ];

                echo json_encode($result,JSON_UNESCAPED_UNICODE);
            }else{

                $result = [
                    'ret' => 4000,
                    'data' => '',
                    'msg' => '商品添加失败'
                ];

                echo json_encode($result,JSON_UNESCAPED_UNICODE);

                throw new Exception('商品添加失败');
            }
        }catch (Exception $e){
            //如果出错，全部回滚
            __logInfo('商品新增的时候异常信息',$e->getMessage());
            $this->goodsStockPrice_model->trans_rollback();

        }

    }


    /**
     * 商品分类新增接口
     */
    public function categoryAdd()
    {


        __logInfo('分类新增',json_encode($_POST,JSON_UNESCAPED_UNICODE));

        $data = [
            'product_categoryId'=> $_POST['productCategoryId'],  //51ck库存id
            'name'=> $_POST['name'],  //分类名
            'level'=> $_POST['level'],  ////分类级别，1为二级分类，2为三级分类
            'parent_id'=> $_POST['parentId'],  //父分类
            'one_category'=> $_POST['oneCategory'],  //分类类型，（2物料包、3书籍、4机器耗材、9打印机租赁、8供应商商品）
            'create_time' => time()
        ];


        $result = $this->goodsCategory_model->addId($data);

        if($result){
            $a = [
                'ret' => 200,
                'data' => '',
                'msg' => '成功'
            ];
        }else{
            $a = [
                'ret' => 4000,
                'data' => '',
                'msg' => '失败'
            ];
        }



        echo json_encode($a,JSON_UNESCAPED_UNICODE);

    }


    /**
     * 商品分类编辑接口
     */
    public function categoryEdit()
    {
        $data = [
            'name'=> $_POST['name'],  //库存
            'update_time' => time()
        ];

        $where = [
            'product_categoryId'=> $_POST['productCategoryId']  //商品库存表Id
        ];

        $this->goodsCategory_model->edit($data,$where);

        $result = [
            'ret' => 200,
            'data' => '',
            'msg' => '成功'
        ];


        echo json_encode($result,JSON_UNESCAPED_UNICODE);

    }


    /**
     * 商品分类删除接口
     */
    public function categoryDel()
    {
        $data = [
            'product_categoryId' => $_POST['productCategoryId'],
        ];

        $this->goodsCategory_model->remove($data);

        $result = [
            'ret' => 200,
            'data' => '',
            'msg' => '成功'
        ];

        echo json_encode($result,JSON_UNESCAPED_UNICODE);
    }


    /**
     * 预警管理列表接口
     */
    public function stockWaringInfos(){


        $stockWaringInfos = json_decode($_POST['stockWaringInfos'],true);


//        $stockWaringInfos = [
//            '0' => [
//                'ckWarnId' => '123123123',   //51CK预警编码
//                'code' => 'asdasdasdasdasd',         //51ck商品编码
//                'name' => '1541456156',         //商品名称
//                'category' =>  '151856156156',     //商品分类
//                'stock' => '151856156156',           //库存
//                'upperLimit' =>  '1111111',   //上限值
//                'status' => 0, //预警状态,默认0
//                'create_time' => time()
//            ],
//            '1' => [
//                'ckWarnId' => '123123123',   //51CK预警编码
//                'code' => 'asdasdasdasdasd',         //51ck商品编码
//                'name' => '1541456156',         //商品名称
//                'scale' => '151856156156',       //商品规格,红,xl,塑料
//                'category' =>  '151856156156',     //商品分类
//                'stock' => '151856156156',           //库存
//                'upperLimit' =>  '1111111',   //上限值
//                'status' => 0, //预警状态,默认0
//                'create_time' => time()
//            ],
//        ];



//        __logInfo('预警数据',$_POST['stockWaringInfos']);

        if($stockWaringInfos){
            foreach ($stockWaringInfos as $k=>$v){
                if(!isset($v['scale'])){
                    $v['scale'] = '';
                }
                $data = [
                    'warnId' => $v['ckWarnId'],   //51CK预警编码
                    'code' => $v['code'],         //51ck商品编码
                    'name' => $v['name'],         //商品名称
                    'scale' => $v['scale'],       //商品规格,红,xl,塑料
                    'category' => $v['category'],     //商品分类
                    'stock' => $v['stock'],           //库存
                    'upperLimit' => $v['upperLimit'],   //上限值
                    'status' => 0, //预警状态,默认0
                    'createTime' => time()
                ];

                $result = $this->warning_model->addId($data);
            }
        }

        if($result){
            $a = [
                'ret' => 200,
                'data' => '',
                'msg' => '成功'
            ];
        }else{
            $a = [
                'ret' => 4000,
                'data' => '',
                'msg' => '失败'
            ];
        }


        echo json_encode($a,JSON_UNESCAPED_UNICODE);
    }

    /**
     * 库存批量修改接口
     */
    public function stockEditBatch(){
        $stockList = json_decode($_POST['stockList'],true);

//        $stockList = [
//            0 => [
//              'productStockPriceId' => "75B7DB8B7DA111E7A96B3497F625B277",
//                'stock' => 80
//            ],
//            1 => [
//                'productStockPriceId' => "B5E1EBA47DA111E7A96B3497F625B277",
//                'stock' => 80
//            ],
//        ];

        $this->goodsStockPrice_model->trans_begin();
        try{
            if($stockList){
                foreach ($stockList as $k=>$v){
                    $data = [
                        'stock' => $v['stock']  //修改的库存数量
                    ];
                    $where = [
                        'product_stock_priceId' => $v['productStockPriceId'], //商品库存表51ck的id
                    ];

                    $result = $this->goodsStockPrice_model->edit($data,$where);

                }
                if($result){
                    // 如果都为真，全部提交
                    $this->goodsStockPrice_model->trans_commit();

                    $result = [
                        'ret' => 200,
                        'data' => '',
                        'msg' => '库存修改成功'
                    ];

                    echo json_encode($result,JSON_UNESCAPED_UNICODE);
                }else{
                    $result = [
                        'ret' => 4000,
                        'data' => '',
                        'msg' => '库存修改失败'
                    ];

                    echo json_encode($result,JSON_UNESCAPED_UNICODE);

                    throw new Exception('库存修改失败');
                }
            }else{
                $result = [
                    'ret' => 4000,
                    'data' => '',
                    'msg' => 'JSON数据解析失败'
                ];

                echo json_encode($result,JSON_UNESCAPED_UNICODE);

                throw new Exception('JSON数据解析失败');
            }
            

            
        }catch (Exception $e){
            //如果出错，全部回滚
            __logInfo('库存批量修改接口',$e->getMessage());
            $this->goodsStockPrice_model->trans_rollback();
        }
       
    }


    //todo 新增编辑51ck库存修改接口curl post请求
    //请求连接 http://47.94.5.201:8080/aisite/productStockPrice/stockEdit

    /*
        productStockPriceId
        stock
    */






    // 根据商品id查询商品规格名接口
    public function getGoodsByStock()
    {
        // 根据第一个id查询数据
        $arg = [
            'product_id' => $_POST['productId']
        ];
//		
        // 查询二级名字
        $stockData = $this->goodsStockPrice_model->getByFieldQueryData('id,specification_group_names', $arg, 1);

        foreach ($stockData as $k => $v) {
            $twoData[$k]['id'] = $v['id'];
            $twoData[$k]['stock'] = explode(',', $v['specification_group_names']);
        }
        // 返回json
        echo json_encode($twoData, JSON_UNESCAPED_UNICODE);
    }



    public function test(){
//        $goodsSpecification = [
//            0 => [
//                'productSpecificationId' => '3E83D8596DF911E7B35000163E32CBE9', //商品组合id
//                'name' => '规格名革命', //规格名
//                'productId' => "3E83D8596DF911E7B35000163E32CBE9", //商品id
//                'parentSpecification' => "3E83D8596DF911E7B35000163E32CBE9", //上级规格（为空即第一级规格）
//                'create_time' => time(),
//            ],
//            1 => [
//                'productSpecificationId' => 2, //商品组合id
//                'name' => '尺寸666', //规格名
//                'productId' => 2, //商品id
//                'parentSpecification' => 1, //上级规格（为空即第一级规格）
//                'create_time' => time(),
//            ],
//            2 => [
//                'productSpecificationId' => 2, //商品组合id
//                'name' => '尺寸666', //规格名
//                'productId' => 2, //商品id
//                'create_time' => time(),
//            ],
//            3 => [
//                'productSpecificationId' => 2, //商品组合id
//                'name' => '尺寸666', //规格名
//                'productId' => 2, //商品id
//                'create_time' => time(),
//            ],
//        ];





//        $goodsStockPrice = [
//            0 => [
//                'productStockPriceId' => 1, //商品库存价格表id
//                'groupNo' => 11236666, //商品规格组合编号随机生成
//                'specificationGroupNames' => '黑色,M', //规格名的组合，多个以“，”隔开, 匹配规格
//                'stock' => 100, //库存
//                'price' => 120, //价格
//                'create_time' => time(),
//            ],
//            1 => [
//                'productStockPriceId' => 2, //商品库存价格表id
//                'groupNo' => 1123777, //商品规格组合编号随机生成
//                'specificationGroupNames' => '黑色,M', //规格名的组合，多个以“，”隔开, 匹配规格
//                'stock' => 1060, //库存
//                'price' => 1203, //价格
//                'create_time' => time(),
//            ],
//        ];



//        $goodsImage = [
//            0 => [
//                'productImageId' => 1, //商品图片Id
//                'productId' => 2, //商品id
//                'filePath' => '2313/1.jpg', //文件路径（不包含ip地址）
//                'isMain' => 1, //0不是主图，1是主图
//                'create_time' => time(),
//                'update_time' => time(),
//            ],
//            1 => [
//                'productImageId' => 2, //商品图片Id
//                'productId' => 2, //商品id
//                'filePath' => '231344444/1.jpg', //文件路径（不包含ip地址）
//                'isMain' => 0, //0不是主图，1是主图
//                'create_time' => time(),
//                'update_time' => time(),
//            ],
//        ];

    }

    //商品分类一级/二级/三级接口
    public function categoryData()
    {
        $data = [
            0 => [
                'category' => 2,
                'name' => '物料包',
            ],
            1 => [
                'category' => 3,
                'name' => '书籍'
            ],
            2 => [
                'category' => 4,
                'name' => '打印机耗材'
            ],
            3 => [
                'category' => 8,
                'name' => '供应商商品'
            ],
            4 => [
                'category' => 9,
                'name' => '打印机租赁'
            ],
        ];

        foreach ($data as $k => $v) {
            $arg = [
                'level' => 2,
                'one_category' => $v['category']
            ];
            //查询二级名字
            $twoData = $this->goodsCategory_model->getByFieldQueryData('id,name,one_category,level,product_categoryId', $arg, 1);

            $data[$k]['two'] = $twoData;
        }
		
//        echo json_encode($data, JSON_UNESCAPED_UNICODE);
//        die;
        foreach ($data as $k2 => $v2) {
            foreach ($v2['two'] as $k3 => $v3) {

                $arg = [
                    'level' => 3,
                    'parent_id' => $v3['product_categoryId'] ?  $v3['product_categoryId'] : $v3['id']
                ];

                // 查询三级名字
                $threeData = $this->goodsCategory_model->getByFieldQueryData('id,name,one_category,level', $arg, 1);

                $data[$k2]['two'][$k3]['three'] = $threeData;

            }
        }


        echo json_encode($data, JSON_UNESCAPED_UNICODE);


//     echo json_encode($data,JSON_UNESCAPED_UNICODE);


    }

    //根据商品分类id查询商品数据接口
    public function goodsByCategory()
    {

        $page_num = $this->config->item('fenye')['pageNum']; //每页的数据
        $page = $_POST['page']; //获取页码数量
        if (!$page) {
            $num = 1;
            $start_position = ($num - 1) * $page_num;
        } else {
            $start_position = ($page - 1) * $page_num;
        }

        switch ($_POST['type']) {
            case 0:
                $where = 0;
                break;
            case 1:
                $where = [
                    'one_category' => $_POST['category']
                ];
                break;
            case 2:
                $where = [
                    'two_category' => $_POST['category']
                ];
                break;
            case 3:
                $where = [
                    'three_category' => $_POST['category']
                ];
                break;

        }
        if(isset($_POST['search']) && $_POST['search']){
            $searchArg = [
                'field' => 'name',
                'arg'=> $_POST['search'],
                'side' => 'both'
            ];
            $goods = $this->goods_model->search($fields = '*',0,$searchArg,$page_num,$start_position);
        }else{
            $goods = $this->goods_model->page('goods', $where, $page_num, $start_position); //limit查询的数据

        }


        if ($goods[0]) {
            $ids = array_column($goods[0], 'id');  //取出ist的id
            $ckIds = array_column($goods[0], 'ckId'); //取出51ck的ckid

            //ist的商品
            foreach ($ids as $v) {
                $arg2 = [
                    'product_id' => $v,
                ];
                //查询ist的是否有规格信息
                $istSpecification[] = $this->goodsStockPrice_model->getByFieldQueryData('id,product_id,stock,specification_group_names,product_stock_priceId', $arg2, 0);
            }

            //51ck的商品
            foreach ($ckIds as $k2 => $v2) {
                $arg4 = [
                    'product_id' => $v2
                ];
                //查询51ck的是否有规格信息
                $ckSpecification[] = $this->goodsStockPrice_model->getByFieldQueryData('id,product_id,stock,specification_group_names,product_stock_priceId', $arg4, 0); //limit查询的数据
            }

            foreach ($istSpecification as $k6 => $v6) {
                foreach ($goods[0] as $k5 => $v5) {
                    if (isset($v6['specification_group_names']) && $v6['specification_group_names'] != '暂无规格' ) {
                        if ($v6['product_id'] != $v5['ckId']) {
                            $goods[0][$k6]['isSpecification'] = 1;
//                            $goods[0][$k6]['product_stock_priceId'] = $v6['product_stock_priceId'];
                            break;
                        }else{


//                            $goods[0][$k10]['product_stock_priceId'] = $v10['product_stock_priceId'];
                        }
                    }else{
                        $goods[0][$k6]['stockpriceid'] = $v6['id'];
                    }
                }
            }
            unset($v5);

//            print_r($istSpecification);
//            print_r(json_encode($goods[0]));
//            die;


            foreach ($ckSpecification as $k10 => $v10) {
                foreach ($goods[0] as $k9 => $v9) {
                    if ($v9['ckId']) {
                        if (isset($v10['specification_group_names']) && $v10['specification_group_names'] != '暂无规格') {
                            if ($v10['product_id'] == $v9['ckId']) {
                                $goods[0][$k10]['isSpecification'] = 1;
//                                $goods[0][$k10]['product_stock_priceId'] = $v10['product_stock_priceId'];
                                break;
                            }
                        }else{
                            //库存价格表的id
                            $goods[0][$k9]['stockpriceid'] = $v10['id'];
                        }
                    }

                }
            }
            unset($v9);
        }

        foreach ($goods[0] as $k12=>$v12){
            $a[0][$k12]['id'] = $v12['id'];
            $a[0][$k12]['product_no'] = $v12['product_no'];
            $a[0][$k12]['name'] = $v12['name'];
            $a[0][$k12]['goodsUnit'] = $v12['goodsUnit'];
            $a[0][$k12]['isSpecification'] = isset($v12['isSpecification']) ? 1 : 0;
            $a[0][$k12]['ckId'] = $v12['ckId'];
            if(isset($v12['stockpriceid']) && $v12['stockpriceid']){
                $a[0][$k12]['stockpriceid'] = $v12['stockpriceid'];
            }else{
                $a[0][$k12]['stockpriceid'] = '';

            }
//            $a[0][$k12]['product_stock_priceId'] = $v12['product_stock_priceId'];

            // 2物料包、3书籍、4机器耗材、8供应商商品、9打印机租
            switch ($v12['one_category']) {
                case 2:
                    $a[0][$k12]['categoryName'] = '物料包';
                    break;
                case 3:
                    $a[0][$k12]['categoryName'] = '书籍';
                    break;
                case 4:
                    $a[0][$k12]['categoryName'] = '机器耗材';
                    break;
                case 8:
                    $a[0][$k12]['categoryName'] = '供应商商品';
                    break;
                case 9:
                    $a[0][$k12]['categoryName'] = '打印机租赁';
                    break;

            }
        }

        $a['pageNum'] = $page_num;
        $a['total_num'] = $goods['total_num'];
        $a['this_page'] = $page;




        echo json_encode($a, JSON_UNESCAPED_UNICODE);

    }

    //通过一级分类的id 查询二级分类的数据接口
    public function twoCategory()
    {
        //根据第一个id查询数据
        $arg = [
            'level' => 2,
            'one_category' => $_POST['oneCategory']
        ];
        //查询二级名字
        $twoData = $this->goodsCategory_model->getByFieldQueryData('id,name,product_categoryId', $arg, 1);

        //返回json
        echo json_encode($twoData, JSON_UNESCAPED_UNICODE);
    }

//通过二级级分类的id 查询二级分类的数据接口
    public function threeCategory()
    {
        $arg = [
            'level' => 3,
            'parent_id' => $_POST['twoCategory']
        ];
        //查询询三级名字
        $threeData = $this->goodsCategory_model->getByFieldQueryData('id,name,product_categoryId', $arg, 1);

        //返回json
        echo json_encode($threeData, JSON_UNESCAPED_UNICODE);
    }

//根据商品id查询商品规格值接口
    public function getGoodsIdByData()
    {

        $arg = [
            'product_id' => $_POST['productId']
        ];

        $stockData = $this->goodsStockPrice_model->getByFieldQueryData('id,group_no,specification_group_names', $arg, 1);


        echo json_encode($stockData, JSON_UNESCAPED_UNICODE);

    }


    //根据商品分类筛选数据
    public function search(){

        $argc = [];

        //查询一级数据
        if(isset($_GET['oneCategory']) && $_GET['oneCategory']){
            $argc += [
                'one_category' => $_GET['oneCategory']
            ];
        }

        //查询二级
        if(isset($_GET['twoCategory']) && $_GET['twoCategory']){
            $argc += [
                'two_category' => $_GET['twoCategory']
            ];
        }

        //查询三级
        if(isset($_GET['threeCategory']) && $_GET['threeCategory']){
            $argc += [
                'three_category' => $_GET['threeCategory']
            ];
        }

//        echo '<pre>';
//        print_r($argc);
//        die;


        if(isset($_GET['search']) && $_GET['search']){
            $searchArg = [
                'field' => 'name',
                'arg'=> $_GET['search'],
                'side' => 'both'
            ];
        }else{
            $searchArg = '';
        }

        $page_num = $this->config->item('fenye')['pageNum']; //每页的数据
        $start_position = ''; //初始数据
        $page = ($this->input->get('page')); //获取页码数量
        if(!$page){
            $num = 1;
            $start_position = ($num - 1) * $page_num;
        }else{
            $start_position = ($page - 1) * $page_num;
        }

        if(!$argc){
            $argc = 0;
        }



        if($searchArg){

            $goods = $this->goods_model->search('*',$argc,$searchArg,$page_num,$start_position);

        }else{
            $goods = $this->goods_model->page('goods',$argc,$page_num,$start_position);
        }

        if ($goods[0]) {
            $ids = array_column($goods[0], 'id');  //取出ist的id
            $ckIds = array_column($goods[0], 'ckId'); //取出51ck的ckid

            //ist的商品
            foreach ($ids as $v) {
                $arg = [
                    'product_id' => $v,
                    'is_main' => 1
                ];
                $arg2 = [
                    'product_id' => $v,
                ];
                //查询ist图片
                $istImage[] = $this->goodsImage_model->getByFieldQueryData('product_id,file_path', $arg, 0);
                //查询ist的是否有规格信息
                $istSpecification[] = $this->goodsStockPrice_model->getByFieldQueryData('product_id,stock,specification_group_names', $arg2, 0);
                //插叙ist库存
                $istStock[] = $this->goodsStockPrice_model->getByFieldQueryData('product_id,stock,specification_group_names', $arg2, 1);
            }

            //51ck的商品
            foreach ($ckIds as $k2 => $v2) {
                $arg3 = [
                    'product_id' => $v2,
                    'is_main' => 1
                ];
                $arg4 = [
                    'product_id' => $v2
                ];
                $ckImage[] = $this->goodsImage_model->getByFieldQueryData('product_id,file_path', $arg3, 0); //limit查询的数据
                //查询51ck的是否有规格信息
                $ckSpecification[] = $this->goodsStockPrice_model->getByFieldQueryData('product_id,stock,specification_group_names', $arg4, 0); //limit查询的数据
                //查询51ck的是否有库存
                $ckStock[] = $this->goodsStockPrice_model->getByFieldQueryData('product_id,stock,specification_group_names', $arg4, 1); //limit查询的数据
            }

//                echo '<pre>';
//                die();
            //循环ist商品的规格和图片,并加入
            foreach ($goods[0] as $k3 => $v3) {
                foreach ($istImage as $k4 => $v4) {
                    //存在并且不为空
                    if (isset($v4['file_path']) && !empty($v4['file_path'])) {
                        //todo 不相等的时候为什么能加进去?
                        if ($v4['product_id'] != $v3['id']) {
                            $goods[0][$k4]['file_path'] = $v4['file_path'];
                        } else {
                            $goods[0][$k4]['file_path'] = 123456;
                        }
                    } else {
                        $goods[0][$k4]['file_path'] = 789;

                    }
                }
            }
            unset($v3);
            foreach ($istSpecification as $k6 => $v6) {
                foreach ($goods[0] as $k5 => $v5) {
                    if (isset($v6['specification_group_names']) && $v6['specification_group_names'] != '暂无规格' ) {
                        if ($v6['product_id'] != $v5['ckId']) {
                            $goods[0][$k6]['isSpecification'] = 1;
                            break;
                        }
                    }
                }
            }
            unset($v5);

            //查询爱思特的所有库存集合
            foreach ($istStock as $k10 => $v10) {
                $istReStock[] = array_sum(array_column($v10, 'stock'));
            }
            unset($v10);
            //并加入其数据中
            foreach ($goods[0] as $k11 => $v11) {
                foreach ($istReStock as $k12 => $v12) {
                    $goods[0][$k12]['stock'] = $v12;
                }
            }
            unset($v11);

//                echo '<pre>';
//                print_r($goods);
//                die();

            //循环51ck商品的规格和图片
            foreach ($goods[0] as $k7 => $v7) {
                foreach ($ckImage as $k8 => $v8) {
                    //存在并且不为空
                    if ($v7['ckId']) {
                        if (isset($v8['file_path']) && !empty($v8['file_path'])) {
                            //todo 不相等的时候为什么能加进去?
//                                __logInfo('produ',$v8['product_id']);
//                                __logInfo('ckId',$v7['ckId']);
                            if ($v8['product_id'] == $v7['ckId']) {
//                                    __logInfo('ckId',$v8['file_path']);

                                $goods[0][$k8]['file_path'] = $v8['file_path'];
                            } else {
                                $goods[0][$k8]['file_path'] = $v8['file_path'];
                            }
                        }
                    }

                }
            }
//                unset($v7);
//                echo '<pre>';
//                print_r($ckSpecification);
//                die;
            //ckSpecification 放入第一层循环，如果又一次为真就break;
            foreach ($ckSpecification as $k10 => $v6) {
                foreach ($goods[0] as $k9 => $v9) {
                    if ($v9['ckId']) {
                        if (isset($v6['specification_group_names']) && $v6['specification_group_names'] != '暂无规格') {
                            if ($v6['product_id'] == $v9['ckId']) {
                                $goods[0][$k10]['isSpecification'] = 1;
                                break;
                            }
                        }
                    }

                }
            }
//            echo '<pre>';
//            print_r($goods);
//            die;
            unset($v9);


            //循环51ck的库存
            foreach ($ckStock as $k13 => $v13) {
                $ckReStock[] = array_sum(array_column($v13, 'stock'));

            }
            unset($v13);
            foreach ($goods[0] as $k14 => $v14) {
                foreach ($ckReStock as $k15 => $v15) {
                    if ($v14['ckId'] && $v15) {
                        $goods[0][$k15]['stock'] = $v15;
                    }
                }
            }

//                echo '<pre>';
//                print_r($goods);
//                die();


            $viewData = [
                'list' => $goods[0],  //这里得到从数据库中的当页数据
                'totalNum' => $goods['total_num'], //这里得到从数据库中的总页数
                'pageNum' => $page_num //每页显示多少条
            ];

        } else {
            $viewData = [
                'list' => '',  //这里得到从数据库中的当页数据
                'totalNum' => $goods['total_num'], //这里得到从数据库中的总页数
                'pageNum' => $page_num //每页显示多少条
            ];
        }


        $goods['pageNum'] = $page_num;
        $goods['this_page'] = $page;




//        echo '<pre>';
//        print_r($supplier);
//        die;
        echo json_encode($goods,JSON_UNESCAPED_UNICODE);

    }


}